/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dao;

import dao.exceptions.IllegalOrphanException;
import dao.exceptions.NonexistentEntityException;
import entities.TestCase;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entities.Problem;
import entities.Run;
import java.util.ArrayList;
import java.util.Collection;

/**
 *
 * @author santiagobaldrich
 */
public class TestCaseJpaController {

    public TestCaseJpaController()
    {
        emf = Persistence.createEntityManagerFactory("UNOJModelPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager()
    {
        return emf.createEntityManager();
    }

    public void create(TestCase testCase)
    {
        if (testCase.getRunCollection() == null)
        {
            testCase.setRunCollection(new ArrayList<Run>());
        }
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Problem problem = testCase.getProblem();
            if (problem != null)
            {
                problem = em.getReference(problem.getClass(), problem.getIdProblem());
                testCase.setProblem(problem);
            }
            Collection<Run> attachedRunCollection = new ArrayList<Run>();
            for (Run runCollectionRunToAttach : testCase.getRunCollection())
            {
                runCollectionRunToAttach = em.getReference(runCollectionRunToAttach.getClass(), runCollectionRunToAttach.getIdRun());
                attachedRunCollection.add(runCollectionRunToAttach);
            }
            testCase.setRunCollection(attachedRunCollection);
            em.persist(testCase);
            if (problem != null)
            {
                problem.getTestCaseCollection().add(testCase);
                problem = em.merge(problem);
            }
            for (Run runCollectionRun : testCase.getRunCollection())
            {
                TestCase oldTestCaseOfRunCollectionRun = runCollectionRun.getTestCase();
                runCollectionRun.setTestCase(testCase);
                runCollectionRun = em.merge(runCollectionRun);
                if (oldTestCaseOfRunCollectionRun != null)
                {
                    oldTestCaseOfRunCollectionRun.getRunCollection().remove(runCollectionRun);
                    oldTestCaseOfRunCollectionRun = em.merge(oldTestCaseOfRunCollectionRun);
                }
            }
            em.getTransaction().commit();
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public void edit(TestCase testCase) throws IllegalOrphanException, NonexistentEntityException, Exception
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            TestCase persistentTestCase = em.find(TestCase.class, testCase.getIdTestCase());
            Problem problemOld = persistentTestCase.getProblem();
            Problem problemNew = testCase.getProblem();
            Collection<Run> runCollectionOld = persistentTestCase.getRunCollection();
            Collection<Run> runCollectionNew = testCase.getRunCollection();
            List<String> illegalOrphanMessages = null;
            for (Run runCollectionOldRun : runCollectionOld)
            {
                if (!runCollectionNew.contains(runCollectionOldRun))
                {
                    if (illegalOrphanMessages == null)
                    {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Run " + runCollectionOldRun + " since its testCase field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null)
            {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (problemNew != null)
            {
                problemNew = em.getReference(problemNew.getClass(), problemNew.getIdProblem());
                testCase.setProblem(problemNew);
            }
            Collection<Run> attachedRunCollectionNew = new ArrayList<Run>();
            for (Run runCollectionNewRunToAttach : runCollectionNew)
            {
                runCollectionNewRunToAttach = em.getReference(runCollectionNewRunToAttach.getClass(), runCollectionNewRunToAttach.getIdRun());
                attachedRunCollectionNew.add(runCollectionNewRunToAttach);
            }
            runCollectionNew = attachedRunCollectionNew;
            testCase.setRunCollection(runCollectionNew);
            testCase = em.merge(testCase);
            if (problemOld != null && !problemOld.equals(problemNew))
            {
                problemOld.getTestCaseCollection().remove(testCase);
                problemOld = em.merge(problemOld);
            }
            if (problemNew != null && !problemNew.equals(problemOld))
            {
                problemNew.getTestCaseCollection().add(testCase);
                problemNew = em.merge(problemNew);
            }
            for (Run runCollectionNewRun : runCollectionNew)
            {
                if (!runCollectionOld.contains(runCollectionNewRun))
                {
                    TestCase oldTestCaseOfRunCollectionNewRun = runCollectionNewRun.getTestCase();
                    runCollectionNewRun.setTestCase(testCase);
                    runCollectionNewRun = em.merge(runCollectionNewRun);
                    if (oldTestCaseOfRunCollectionNewRun != null && !oldTestCaseOfRunCollectionNewRun.equals(testCase))
                    {
                        oldTestCaseOfRunCollectionNewRun.getRunCollection().remove(runCollectionNewRun);
                        oldTestCaseOfRunCollectionNewRun = em.merge(oldTestCaseOfRunCollectionNewRun);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex)
        {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0)
            {
                Integer id = testCase.getIdTestCase();
                if (findTestCase(id) == null)
                {
                    throw new NonexistentEntityException("The testCase with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            TestCase testCase;
            try
            {
                testCase = em.getReference(TestCase.class, id);
                testCase.getIdTestCase();
            } catch (EntityNotFoundException enfe)
            {
                throw new NonexistentEntityException("The testCase with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<Run> runCollectionOrphanCheck = testCase.getRunCollection();
            for (Run runCollectionOrphanCheckRun : runCollectionOrphanCheck)
            {
                if (illegalOrphanMessages == null)
                {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This TestCase (" + testCase + ") cannot be destroyed since the Run " + runCollectionOrphanCheckRun + " in its runCollection field has a non-nullable testCase field.");
            }
            if (illegalOrphanMessages != null)
            {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Problem problem = testCase.getProblem();
            if (problem != null)
            {
                problem.getTestCaseCollection().remove(testCase);
                problem = em.merge(problem);
            }
            em.remove(testCase);
            em.getTransaction().commit();
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public List<TestCase> findTestCaseEntities()
    {
        return findTestCaseEntities(true, -1, -1);
    }

    public List<TestCase> findTestCaseEntities(int maxResults, int firstResult)
    {
        return findTestCaseEntities(false, maxResults, firstResult);
    }

    private List<TestCase> findTestCaseEntities(boolean all, int maxResults, int firstResult)
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(TestCase.class));
            Query q = em.createQuery(cq);
            if (!all)
            {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally
        {
            em.close();
        }
    }

    public TestCase findTestCase(Integer id)
    {
        EntityManager em = getEntityManager();
        try
        {
            return em.find(TestCase.class, id);
        } finally
        {
            em.close();
        }
    }

    public int getTestCaseCount()
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<TestCase> rt = cq.from(TestCase.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally
        {
            em.close();
        }
    }

}
